package com.ghsc.ghxc.jsb.ui.my.activity

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.OSS
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.ApkUtil
import com.cn.appcore.utils.GlideEngine
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.cn.appcore.utils.TimeUtils
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivitySetUpBinding
import com.ghsc.ghxc.jsb.ext.showCustomPopup
import com.ghsc.ghxc.jsb.ui.login.AgreementActivity
import com.ghsc.ghxc.jsb.ui.login.RetrievePwdActivity
import com.ghsc.ghxc.jsb.ui.my.bean.UserBeanData
import com.ghsc.ghxc.jsb.utils.CleanDataUtils
import com.ghsc.ghxc.jsb.utils.OssUpUtils
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.ghsc.ghxc.jsb.view.CenterSelectPopup
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.permissionx.guolindev.PermissionX
import com.scwang.smart.refresh.layout.api.RefreshLayout
import java.util.ArrayList
import java.util.HashMap
import java.util.Objects

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.my.activity
 * 类名：SetUpActivity
 * 创建时间：2024/4/24 20:07
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 设置
 */
class SetUpActivity  : BaseVMActivity<SetUpViewModel, ActivitySetUpBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_set_up
    }

    override fun attachVMClass(): Class<SetUpViewModel>? {
        return SetUpViewModel::class.java
    }
    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }


    var userInfo : UserBeanData?=null

    val CHOOSE_PHOTO_1 = 1001
    private var selectHead: List<LocalMedia> = ArrayList()
    var pathHead = "" //头像地址
    private var themeId = 0


    //上传到阿里云服务器到图片url
    var aliUrlHead=""

    var versionName:String="" //版本


    var userId: String by Preference(HttpConstant.USER_ID, "")
    override fun onResume() {
        super.onResume()
        getListData()

    }


    override fun initView() {
        binding.refreshLayout.setEnableLoadMore(false)
        initRefreshLayout()
        val clearSize = CleanDataUtils.getTotalCacheSize(Objects.requireNonNull(this))
        versionName= ApkUtil.getVersionName()
        binding.run {
            tvName.hint="修改"
            tvPhone.hint="未登陆"
            tvAccountAuth.hint="未认证"
            tvPaymentType.hint="添加"
            tvAddress.hint="添加"
            tvLoginpwd.hint="修改"
            tvPayPwd.hint="修改"
            tvAccountAppeal.hint="申诉"
            tvAgreement.hint="查看"
            tvPolicy.hint="查看"
            binding.tvCache.text= "$clearSize M"
            tvEdition.text= "V $versionName"
        }
        themeId= R.style.picture_default_style
        initRefreshLayout()
    }


    /**
     * 获取个人信息
     */
    private fun getListData() {
        mViewModel.onUserInfoMethod()
    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {

            }
        })
    }

    override fun initData() {
        super.initData()
        binding.run {
            bar.topTitle.text="设置"
            bar.topLeftView.setOnClickListener { finish() }
            llBtnHead.setSingleClickListener {
                //头像
                PictureSelector.create(this@SetUpActivity)
                    .openGallery(PictureMimeType.ofImage())
                    .loadImageEngine(GlideEngine.createGlideEngine())
                    .theme(themeId)
                    .selectionMode(PictureConfig.SINGLE)
                    .imageSpanCount(4)
                    .previewImage(true)
                    .isCamera(true)
                    .enableCrop(false) // 是否裁剪
                    .compress(true) // 是否压缩
                    .freeStyleCropEnabled(true) // 裁剪框是否可拖拽
                    .scaleEnabled(true)
//                .cropWH(345,128)// 裁剪宽高比，设置如果大于图片本身宽高则无效
//                .cropImageWideHigh()//
                    .minimumCompressSize(100) // 小于100kb的图片不压缩
                    .forResult(CHOOSE_PHOTO_1)
            }
            llBtnName.setSingleClickListener {
                //昵称
                var bundle= Bundle()
                bundle.putString("nickName",binding.tvName.text.toString().trim())
                startActivity(UpNicknameInfoActivity().javaClass,bundle)

            }
            llBtnLoginPwd.setSingleClickListener {
                //修改登录密码
                var bundle = Bundle()
                bundle.putInt("sign",1)
                startActivity(RetrievePwdActivity().javaClass,bundle)
            }
            llBtnPayPwd.setSingleClickListener {
                //修改资产密码
                startActivity(UpPayPwdActivity().javaClass)
            }
            llBtnAgreement.setSingleClickListener {
                //用户服务协议
                var bundle = Bundle()
                bundle.putInt("sign",1)
                startActivity(AgreementActivity().javaClass,bundle)

            }
            llBtnPolicy.setSingleClickListener {
                //隐私政策
                var bundle = Bundle()
                bundle.putInt("sign",2)
                startActivity(AgreementActivity().javaClass,bundle)
            }
            llBtnCache.setSingleClickListener {
                //缓存
                XPopup.Builder(this@SetUpActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .customHostLifecycle(lifecycle)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        ConfirmCancelPopViiew(this@SetUpActivity,"提示","确定清空缓存?",
                            btnConfirm={
                                CleanDataUtils.clearAllCache(this@SetUpActivity)
                                val clearSize = CleanDataUtils.getTotalCacheSize(
                                    Objects.requireNonNull(this@SetUpActivity))
                                binding.tvCache.text= "$clearSize M"
                                showToast("缓存清理成功！")
                            },
                            btnCancel={
                            },)
                    )
                    .show()
            }
            llBtnEdition.setSingleClickListener {
                //版本
                mViewModel.onSysConfigMethod("")
            }
            llBtnAboutUs.setSingleClickListener {
                //关于我们
                startActivity(AboutUsActivity().javaClass)
            }
            tvBtnOut.setSingleClickListener {
                //退出
                XPopup.Builder(this@SetUpActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .customHostLifecycle(lifecycle)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        ConfirmCancelPopViiew(this@SetUpActivity,"提示","确定要退出当前账号吗?",
                            btnConfirm={
                                LoginHelper.startLoginPage(this@SetUpActivity)
                            },
                            btnCancel={
                            },)
                    )
                    .show()
            }
            tvBtnDelete.setSingleClickListener {
                //删除账号
                startActivity(LogOffActivity().javaClass)
            }
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {

            errorMsg.observe(this@SetUpActivity) {
                binding.refreshLayout.finishRefresh()
                showToast( it)
            }
            againLoginMsg.observe(this@SetUpActivity) {
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }


            onSysConfigData.observe(this@SetUpActivity) {

            }
            onUserInfoData.observe(this@SetUpActivity) {
                binding.refreshLayout.finishRefresh()
                binding.run {
                    userInfo =it.data.data
                    userInfo?.let {
                        GlideUtil.ImageHeadLoad(this@SetUpActivity,it.headimg,imgHead)
                        tvName.text= it.nickname
                        tvPhone.text=it.mobile
                        tvAddress.text="添加"
                        tvLoginpwd.text="修改"
                        tvPayPwd.text="设置"
                        tvAccountAppeal.text="申诉"
                        tvAgreement.text="查看"
                        tvPolicy.text="查看"

                    }
                }
            }
            onAliYunOosData.observe(this@SetUpActivity) {
                var oss=  OssUpUtils.ossConfig(this@SetUpActivity,
                    it.data.ossHost,it.data.AccessKeyId,it.data.AccessKeySecret,it.data.SecurityToken)
                loge("头像="+pathHead)
                aliUrlHead=it.data.rootPATH+ CustKey.IMG_URL_HEAD+ StringUtil.getTime()+"/"+userId+ TimeUtils.getTime10()+(0..100).random()+".png"
                loge("头像=--===="+aliUrlHead)
                upload(oss,it.data.bucketName, pathHead,aliUrlHead)
            }
            updateUserInfoData.observe(this@SetUpActivity) {
                dismissLoading()
                showToast("修改成功")
                getListData()
            }
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            RESULT_OK -> when (requestCode) {
                CHOOSE_PHOTO_1 -> {
                    // 图片选择结果回调
                    selectHead = PictureSelector.obtainMultipleResult(data)
                    for (media in selectHead) {
                        Log.i("图片-----》", media.path)
                        pathHead = if (media.isCut && !media.isCompressed) {
                            // 裁剪过
                            media.cutPath
                        } else if (media.isCompressed || media.isCut && media.isCompressed) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                            media.compressPath
                        } else {
                            // 原图
                            media.path
                        }

                        GlideUtil.ImageHeadLoad(this,pathHead,binding.imgHead)
                        //todo 上传头像
                        showLoading()
                        mViewModel.onAliYunOosMethod("")
                    }
                }
            }
            else -> {
            }
        }
    }
    /**
     * bucketName 仓库名
     * uploadFilePath  阿里服务器的路径
     * objectName  图片地址
     */
    fun upload(oss: OSS, bucketName:String, objectName:String, uploadFilePath:String){
        /**
         * bucketName
         * uploadFilePath 后台给的路径。是放在阿里服务器的某个路径下
         * objectName 本地上传的路径。比如上传的xxx/xxx/xxx.png
         */
        val put = PutObjectRequest(bucketName, uploadFilePath,objectName)
        // 异步上传时可以设置进度回调。
        put.progressCallback =
            OSSProgressCallback { request, currentSize, totalSize ->
            }
        val task: OSSAsyncTask<*> = oss.asyncPutObject(
            put,
            object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
                override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult) {
                    loge("onSuccess-ETag"+result.eTag)
//                    loge("onSuccess-RequestId"+result.requestId)
//                    loge("onSuccess-result："+result.toString())
//                    loge("onSuccess-uploadFilePath"+request!!.uploadFilePath)
//                    loge("onSuccess-uploadUri"+request.uploadUri)


                    userInfo?.let {
                        val map: HashMap<String, Any> = HashMap()
//                        map["nickname"] = it.nickname
                        map["headimg"] =if (!TextUtils.isEmpty(aliUrlHead))  aliUrlHead else it.headimg
                        mViewModel.updateUserInfoMethod(GsonUtil.mapToJsonStrObjEncryption(map)!!)
                    }


                }
                override fun onFailure(
                    request: PutObjectRequest?,
                    clientExcepion: ClientException,
                    serviceException: ServiceException
                ) {
                    // 请求异常。
                    if (clientExcepion != null) {
                        // 客户端异常，例如网络异常等。
                        clientExcepion.printStackTrace()
                    }
                    if (serviceException != null) {
                        // 服务端异常。
                        Log.e("onFailure-ErrorCode", serviceException.errorCode)
                        Log.e("onFailure-RequestId", serviceException.requestId)
                        Log.e("onFailure-HostId", serviceException.hostId)
                        Log.e("onFailure-RawMessage", serviceException.rawMessage)
                    }
                    dismissLoading()
                    showToast("上传失败，请重试...")
                }
            })
//        取消上传任务。
//        task.cancel();
//        等待上传任务完成。
//        task.waitUntilFinished();
    }
}